package com.example.demo.service;

import com.example.demo.dao.UserDao;
import com.example.demo.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author zhouzhenyuan
 */
@Service
public class UserCacheApiService {
    @Autowired
    private UserDao userDao;

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    public User findById (String userId) {
        Object object = redisTemplate.opsForValue().get("user_"+userId);
        if (object!=null) {
            return (User) object;
        } else {
            User user = userService.getUserById(userId);
            if (user != null) {
                redisTemplate.opsForValue().set("user_"+userId,userId,1, TimeUnit.DAYS);
                return user;
            }
        }
        return null;
    }

    public User updateUser(User user) {
        userDao.updateUserByUserId(user.getEmail(),user.getUserId());
        redisTemplate.opsForValue().set("user_"+user.getUserId(),user);
        return user;
    }

    public void deleteUser(String userId) {
        userDao.deleteById(userId);
        redisTemplate.delete("user_id"+userId);
    }
}
